package io.renren.modules.seller.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.seller.dao.*;
import io.renren.modules.seller.entity.*;
import io.renren.modules.seller.group.Goods;
import io.renren.modules.seller.service.GoodsService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 */
@Service("goodsService")
@Transactional(rollbackFor = Exception.class)
public class GoodsServiceImpl extends ServiceImpl<GoodsDao, GoodsEntity> implements GoodsService {

    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private GoodsDescDao goodsDescDao;
    @Autowired
    private ItemDao itemDao;
    @Autowired
    private ItemCatDao itemCatDao;
    @Autowired
    private BrandDao brandDao;
    @Autowired
    private SellerDao sellerDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<GoodsEntity> page = this.page(
                new Query<GoodsEntity>().getPage(params),
                new QueryWrapper<GoodsEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageResult findPage(Map<String, Object> params) {
        IPage<GoodsEntity> page = this.page(
                new Query<GoodsEntity>().getPage(params),
                new QueryWrapper<>());
        return new PageResult(page.getTotal(), page.getRecords());
    }

    @Override
    public void deleteByIds(Long[] ids) {
        goodsDao.batchDel(ids);
    }

    @Override
    public Goods findOne(Long id) {
        Goods goods = new Goods();
        //商品基本表
        GoodsEntity tbGoods = this.getById(id);
        goods.setGoods(tbGoods);
        //商品扩展表
        GoodsDescEntity goodsDesc = goodsDescDao.selectById(id);
        goods.setGoodsDesc(goodsDesc);
        //读取SKU列表
        Wrapper<ItemEntity> wrapper = new QueryWrapper<ItemEntity>().eq("goods_id", id);
        List<ItemEntity> itemList = itemDao.selectList(wrapper);
        goods.setItemList(itemList);
        return goods;
    }

    @Override
    public PageResult findPage(GoodsEntity goods, String page, String limit) {
        // 分页参数
        HashMap<String, Object> params = new HashMap<>(8);
        params.put("page", page);
        params.put("limit", limit);
        // 条件查询
        String sellerId = goods.getSellerId();
        String goodsName = goods.getGoodsName();
        String auditStatus = goods.getAuditStatus();
        String isMarketable = goods.getIsMarketable();
        String caption = goods.getCaption();
        String smallPic = goods.getSmallPic();
        String isEnableSpec = goods.getIsEnableSpec();
        String isDelete = goods.getIsDelete();
        IPage<GoodsEntity> iPage = this.page(
                new Query<GoodsEntity>().getPage(params),
                new QueryWrapper<GoodsEntity>()
                        .eq(StringUtils.isNotBlank(sellerId), "seller_id", sellerId)
                        .like(StringUtils.isNotBlank(goodsName), "goods_name", goodsName)
                        .eq(StringUtils.isNotBlank(auditStatus), "audit_status", auditStatus)
                        .eq(StringUtils.isNotBlank(isMarketable), "is_marketable", isMarketable)
                        .like(StringUtils.isNotBlank(caption), "caption", caption)

        );
        return new PageResult(iPage.getTotal(), iPage.getRecords());
    }

    @Override
    public void update(Goods goods) {
        //更新基本表数据
        this.updateById(goods.getGoods());
        //更新扩展表数据
        goodsDescDao.updateById(goods.getGoodsDesc());
        //删除原有的SKU列表数据
        Wrapper<ItemEntity> wrapper = new QueryWrapper<ItemEntity>().eq("goods_id", goods.getGoods().getId());
        itemDao.delete(wrapper);
        //插入新的SKU列表数据
        saveItemList(goods);
    }

    @Override
    public void add(Goods goods) {
        //状态：0-未审核
        goods.getGoods().setAuditStatus("0");
        //插入商品基本信息
        this.save(goods.getGoods());
        //将商品基本表的ID给商品扩展表
        goods.getGoodsDesc().setGoodsId(goods.getGoods().getId());
        //插入商品扩展表数据
        goodsDescDao.insert(goods.getGoodsDesc());
        //插入SKU商品数据
        saveItemList(goods);
    }

    @Override
    public void updateStatus(Long[] ids, String auditStatus) {
        goodsDao.updateStatus(ids, auditStatus);
    }

    /**
     * //插入sku列表数据
     *
     * @param goods goods
     */
    private void saveItemList(Goods goods) {
        if ("1".equals(goods.getGoods().getIsEnableSpec())) {
            for (ItemEntity item : goods.getItemList()) {
                //构建标题  SPU名称+ 规格选项值
                //SPU名称
                String title = goods.getGoods().getGoodsName();
                Map<String, Object> map = JSON.parseObject(item.getSpec());
                for (String key : map.keySet()) {
                    title += " " + map.get(key);
                }
                item.setTitle(title);
                setItemValues(item, goods);
                itemDao.insert(item);
            }
        } else {
            //没有启用规格
            ItemEntity item = new ItemEntity();
            item.setTitle(goods.getGoods().getGoodsName());//标题
            item.setPrice(goods.getGoods().getPrice());//价格
            item.setNum(99999);//库存数量
            item.setStatus("1");//状态
            item.setIsDefault("1");//默认
            item.setSpec("{}");//规格
            setItemValues(item, goods);
            itemDao.insert(item);
        }
    }

    private void setItemValues(ItemEntity item, Goods goods) {
        //商品分类
        item.setCategoryid(goods.getGoods().getCategory3Id());//三级分类ID
        item.setCreateTime(new Date());//创建日期
        item.setUpdateTime(new Date());//更新日期

        item.setGoodsId(goods.getGoods().getId());//商品ID
        item.setSellerId(goods.getGoods().getSellerId());//商家ID

        //分类名称
        ItemCatEntity itemCat = itemCatDao.selectById(goods.getGoods().getCategory3Id());
        item.setCategory(itemCat.getName());
        //品牌名称
        BrandEntity brand = brandDao.selectById(goods.getGoods().getBrandId());
        item.setBrand(brand.getName());
        //商家名称(店铺名称)
        SellerEntity seller = sellerDao.selectById(goods.getGoods().getSellerId());
        item.setSeller(seller.getNickName());
        //图片
        List<Map> imageList = JSON.parseArray(goods.getGoodsDesc().getItemImages(), Map.class);
        if (imageList.size() > 0) {
            item.setImage((String) imageList.get(0).get("url"));
        }
    }
}
